package besta.moon.engine.selector.result;

import java.sql.SQLException;

import besta.moon.MoonException;
import besta.moon.MoonConnection;
import besta.moon.engine.RowSource;
import besta.moon.engine.Table;
import besta.moon.engine.View;
import besta.moon.engine.ViewTable;
import besta.moon.engine.selector.DataSource;
import besta.moon.engine.selector.multioper.Where;
import besta.moon.sql.Expression;
import besta.moon.sql.parser.SQLTokenizer;
import besta.moon.MoonCode;


public abstract class TableViewResult extends DataSource {

    protected MoonConnection con;

    private String alias;
    private long tableTimestamp;
    public int lock = SQLTokenizer.SELECT;

    public static TableViewResult createResult(View tableView) {
        if (tableView instanceof Table) {
            return new TableResult((Table) tableView);
        }
        return new ViewResult((ViewTable) tableView);
    }

    public static TableViewResult getTableViewResult(RowSource from) throws SQLException {
        if (from instanceof Where) {
            from = ((Where) from).getFrom();
        }
        if (from instanceof TableViewResult) {
            return (TableViewResult) from;
        }
        throw MoonException.create(MoonCode.ROWSOURCE_READONLY);
    }

    @Override
    public void setAlias(String alias) {
        this.alias = alias;
    }

    @Override
    public String getAlias() {
        return (alias != null) ? alias : getTableView().name;
    }

    @Override
    public boolean hasAlias() {
        return alias != null;
    }

    @Override
    public boolean init(MoonConnection con) throws Exception {
        View tableView = getTableView();
        if (tableTimestamp != tableView.getTimestamp()) {
            this.con = con;
            tableTimestamp = tableView.getTimestamp();
            return true;
        }
        return false;
    }

    public abstract void deleteRow() throws SQLException;

    public abstract void updateRow(Expression[] updateValues) throws Exception;

    public abstract void insertRow(Expression[] updateValues) throws Exception;

    @Override
    public final boolean isScrollable() {
        return false;
    }

}
